package org.webby.alert;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * A filter that puts the alert (if any) into a request attribute. Requires the 'alertService' attribute to be set
 * in the servlet context prior to initialization.
 */
public class AlertFilter implements Filter {
  private AlertService alertService;

  public void init(FilterConfig config) throws ServletException {
    alertService = (AlertService) config.getServletContext().getAttribute(AlertService.servletContextAttributeName);
    if (alertService == null) {
      throw new ServletException("missing required attribute " + AlertService.servletContextAttributeName);
    }
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
      assert response instanceof HttpServletResponse;
      alertService.processRequest((HttpServletRequest) request, (HttpServletResponse) response);
    }
    chain.doFilter(request, response);
  }

  public void destroy() {
  }
}
